package base.thread_JUC2.chapter03.demo06;

import base.util.Util;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Phaser;

@Slf4j
public class Student implements Runnable{

    private Phaser phaser;

    public Student(Phaser phaser){
        this.phaser = phaser;
    }

    /**
     * 与 MyPhaser中的 onAdvance()方法轮流交替执行
     */
    @Override
    public void run() {
        log.info("{} 到达考试现场,等待开考", Thread.currentThread().getName());
        phaser.arriveAndAwaitAdvance();//每个阶段的最后一个线程执行这个方法都会去唤醒所有因phaser而导致等待的线程,同时phaser状态改变，调用onAdvance()方法

        log.info("{} 开始做第一个测试", Thread.currentThread().getName());
        doExercise1();

        log.info("{} 等待做第二测试", Thread.currentThread().getName());
        phaser.arriveAndAwaitAdvance();

        log.info("{} 开始做第二测试", Thread.currentThread().getName());
        doExercise2();
        
        log.info("{} 等待做第三测试", Thread.currentThread().getName());
        phaser.arriveAndAwaitAdvance();

        log.info("{} 开始做第三测试", Thread.currentThread().getName());
        doExercise3();

        // 等待一起结束
        phaser.arriveAndAwaitAdvance();
    }

    private void doExercise3() {
        Util.sleepX(Util.randomInt(1,5));
    }

    private void doExercise2() {
        Util.sleepX(Util.randomInt(1,5));
    }

    private void doExercise1() {
        Util.sleepX(Util.randomInt(1,5));
    }

}
